package com.zhiyizhen.handheld.component.main;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import androidx.activity.OnBackPressedCallback;
import androidx.fragment.app.FragmentTransaction;

import com.zhiyizhen.handheld.R;
import com.zhiyizhen.handheld.common.AppUtil;
import com.zhiyizhen.handheld.common.DataCache;
import com.zhiyizhen.handheld.common.ImageLoader;
import com.zhiyizhen.handheld.common.ResourcesUtil;
import com.zhiyizhen.handheld.common.RxJavaUtil;
import com.zhiyizhen.handheld.common.constant.AppConstant;
import com.zhiyizhen.handheld.common.event.UpdateMessageCountEvent;
import com.zhiyizhen.handheld.common.view.BaseActivity;
import com.zhiyizhen.handheld.common.view.CommonDialog;
import com.zhiyizhen.handheld.component.execute.ExecuteFragment;
import com.zhiyizhen.handheld.component.login.bean.LoginBean;
import com.zhiyizhen.handheld.component.main.api.IMainService;
import com.zhiyizhen.handheld.component.main.bean.ClinicInfo;
import com.zhiyizhen.handheld.component.main.bean.MenuItemBean;
import com.zhiyizhen.handheld.component.message.MessageFragment;
import com.zhiyizhen.handheld.component.personal.PersonalInfoFragment;
import com.zhiyizhen.handheld.component.personal.view.RightAnchorPopupHelper;
import com.zhiyizhen.handheld.component.pharmacy.PharmacyFragment;
import com.zhiyizhen.handheld.component.workspace.WorkspaceFragment;
import com.zhiyizhen.handheld.databinding.ActivityMainBinding;
import com.zhiyizhen.handheld.net.ServiceFactory;
import com.zhiyizhen.handheld.net.response.ResponseData;
import com.zhiyizhen.handheld.net.response.ResponseObserver;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * description 首页
 */
public class MainActivity extends BaseActivity {
    private ActivityMainBinding binding;
    private FragmentTransaction fragmentTransaction;
    private WorkspaceFragment workspaceFragment;
    private ExecuteFragment executeFragment;
    private PharmacyFragment pharmacyFragment;
    private MessageFragment messageFragment;
    private PersonalInfoFragment personalInfoFragment;

    private final static int workspaceFragmentIndex = 1;
    private final static int executeFragmentIndex = 2;
    private final static int pharmacyFragmentIndex = 3;
    private final static int messageFragmentIndex = 4;
    private final static int personalInfoFragmentIndex = 5;

    private int currentIndex = 0;
    private LoginBean loginBean;
    private static List<MenuItemBean> menuList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        loginBean = DataCache.getLoginBean();

        workspaceFragment = new WorkspaceFragment();
        executeFragment = new ExecuteFragment();
        pharmacyFragment = new PharmacyFragment();
        messageFragment = new MessageFragment();
        personalInfoFragment = new PersonalInfoFragment();

        fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.fragment_container, workspaceFragment);
        fragmentTransaction.add(R.id.fragment_container, executeFragment);
        fragmentTransaction.add(R.id.fragment_container, pharmacyFragment);
        fragmentTransaction.add(R.id.fragment_container, messageFragment);
        fragmentTransaction.add(R.id.fragment_container, personalInfoFragment);
        hideFragments(fragmentTransaction, workspaceFragmentIndex);
        showWorkspaceFragment(fragmentTransaction);

        binding.workspaceLayout.setOnClickListener(view -> {
            if (currentIndex == workspaceFragmentIndex) {
                return;
            }
            fragmentTransaction = getSupportFragmentManager().beginTransaction();
            hideFragments(fragmentTransaction, workspaceFragmentIndex);
            showWorkspaceFragment(fragmentTransaction);

        });
        binding.executeLayout.setOnClickListener(view -> {
            if (currentIndex == executeFragmentIndex) {
                return;
            }
            fragmentTransaction = getSupportFragmentManager().beginTransaction();
            hideFragments(fragmentTransaction, executeFragmentIndex);
            showExecuteFragment(fragmentTransaction);
        });
        binding.pharmacyLayout.setOnClickListener(view -> {
            if (currentIndex == pharmacyFragmentIndex) {
                return;
            }
            fragmentTransaction = getSupportFragmentManager().beginTransaction();
            hideFragments(fragmentTransaction, pharmacyFragmentIndex);
            showPharmacyFragment(fragmentTransaction);
        });
        binding.messageLayout.setOnClickListener(view -> {
            if (currentIndex == messageFragmentIndex) {
                return;
            }
            fragmentTransaction = getSupportFragmentManager().beginTransaction();
            hideFragments(fragmentTransaction, messageFragmentIndex);
            showMessageFragment(fragmentTransaction);
        });
        binding.personalInfoLayout.setOnClickListener(view -> showPersonDialog());

        getClinicInfo();
        getUnreadNum();
        setMenu();
        back();
    }

    private void back() {
        // 注册返回事件回调
        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                showLogoutDialog();
            }
        });
    }

    private void showPersonDialog() {
        PopupWindow popupWindow = RightAnchorPopupHelper.showRightAnchor(this, binding.personalInfoLayout, R.layout.popup_personal);
        View contentView = popupWindow.getContentView();
        LinearLayout personalBtn = contentView.findViewById(R.id.personalBtn);
        LinearLayout logoutBtn = contentView.findViewById(R.id.logoutBtn);
        personalBtn.setOnClickListener(v -> {
            if (currentIndex == personalInfoFragmentIndex) {
                return;
            }
            fragmentTransaction = getSupportFragmentManager().beginTransaction();
            hideFragments(fragmentTransaction, personalInfoFragmentIndex);
            showPersonalInfoFragment(fragmentTransaction);
            popupWindow.dismiss();
        });

        logoutBtn.setOnClickListener(v -> {
            popupWindow.dismiss();
            showLogoutDialog();
        });
    }

    private CommonDialog dialog;

    public void showLogoutDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_logout, (ViewGroup) this.getWindow().getDecorView(), false);

        CommonDialog.Builder builder = new CommonDialog.Builder(this);
        builder.setView(view);

        builder.setCancelable(false);
        dialog = builder.show();

        view.findViewById(R.id.cancel_btn).setOnClickListener(v -> dialog.dismiss());
        view.findViewById(R.id.ok_btn).setOnClickListener(v -> {
            dialog.dismiss();
            AppUtil.relogin();
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void hideFragments(FragmentTransaction fragmentTransaction, int selectIndex) {
        if (selectIndex == workspaceFragmentIndex) {
            fragmentTransaction.hide(executeFragment);
            fragmentTransaction.hide(pharmacyFragment);
            fragmentTransaction.hide(messageFragment);
            fragmentTransaction.hide(personalInfoFragment);
        } else if (selectIndex == executeFragmentIndex) {
            fragmentTransaction.hide(workspaceFragment);
            fragmentTransaction.hide(pharmacyFragment);
            fragmentTransaction.hide(messageFragment);
            fragmentTransaction.hide(personalInfoFragment);
        } else if (selectIndex == pharmacyFragmentIndex) {
            fragmentTransaction.hide(workspaceFragment);
            fragmentTransaction.hide(executeFragment);
            fragmentTransaction.hide(messageFragment);
            fragmentTransaction.hide(personalInfoFragment);
        } else if (selectIndex == messageFragmentIndex) {
            fragmentTransaction.hide(workspaceFragment);
            fragmentTransaction.hide(executeFragment);
            fragmentTransaction.hide(pharmacyFragment);
            fragmentTransaction.hide(personalInfoFragment);
        } else if (selectIndex == personalInfoFragmentIndex) {
            fragmentTransaction.hide(workspaceFragment);
            fragmentTransaction.hide(executeFragment);
            fragmentTransaction.hide(pharmacyFragment);
            fragmentTransaction.hide(messageFragment);
        }
    }

    private void showWorkspaceFragment(FragmentTransaction fragmentTransaction) {
        currentIndex = workspaceFragmentIndex;
        fragmentTransaction.show(workspaceFragment);
        fragmentTransaction.commit();

        binding.workspaceLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.white_33));
        binding.executeLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.pharmacyLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.messageLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.personalInfoLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));

        binding.workspaceImg.setSelected(true);
        binding.executeImg.setSelected(false);
        binding.pharmacyImg.setSelected(false);
        binding.messageImg.setSelected(false);
        binding.personalInfoImg.setSelected(false);
    }

    private void showExecuteFragment(FragmentTransaction fragmentTransaction) {
        currentIndex = executeFragmentIndex;
        fragmentTransaction.show(executeFragment);
        fragmentTransaction.commit();

        binding.workspaceLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.executeLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.white_33));
        binding.pharmacyLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.messageLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.personalInfoLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));

        binding.workspaceImg.setSelected(false);
        binding.executeImg.setSelected(true);
        binding.pharmacyImg.setSelected(false);
        binding.messageImg.setSelected(false);
        binding.personalInfoImg.setSelected(false);
    }

    private void showPharmacyFragment(FragmentTransaction fragmentTransaction) {
        currentIndex = pharmacyFragmentIndex;
        fragmentTransaction.show(pharmacyFragment);
        fragmentTransaction.commit();

        binding.workspaceLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.executeLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.pharmacyLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.white_33));
        binding.messageLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.personalInfoLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));

        binding.workspaceImg.setSelected(false);
        binding.executeImg.setSelected(false);
        binding.pharmacyImg.setSelected(true);
        binding.messageImg.setSelected(false);
        binding.personalInfoImg.setSelected(false);
    }

    private void showMessageFragment(FragmentTransaction fragmentTransaction) {
        currentIndex = messageFragmentIndex;
        fragmentTransaction.show(messageFragment);
        fragmentTransaction.commit();

        binding.workspaceLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.executeLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.pharmacyLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.messageLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.white_33));
        binding.personalInfoLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));

        binding.workspaceImg.setSelected(false);
        binding.executeImg.setSelected(false);
        binding.pharmacyImg.setSelected(false);
        binding.messageImg.setSelected(true);
        binding.personalInfoImg.setSelected(false);
    }

    private void showPersonalInfoFragment(FragmentTransaction fragmentTransaction) {
        currentIndex = personalInfoFragmentIndex;
        fragmentTransaction.show(personalInfoFragment);
        fragmentTransaction.commitAllowingStateLoss();

        binding.workspaceLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.executeLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.pharmacyLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.messageLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.transparent));
        binding.personalInfoLayout.setBackgroundColor(ResourcesUtil.getColor(R.color.white_33));

        binding.workspaceImg.setSelected(false);
        binding.executeImg.setSelected(false);
        binding.pharmacyImg.setSelected(false);
        binding.messageImg.setSelected(false);
        binding.personalInfoImg.setSelected(true);
    }

    private void getClinicInfo() {
        if (loginBean == null) {
            return;
        }
        ServiceFactory.getService(IMainService.class)
                .getClinicInfo(loginBean.getToken(), loginBean.getClinicId())
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<ClinicInfo> responseData) {
                        if (responseData != null) {
                            ImageLoader.load(MainActivity.this, responseData.getData().getLogo(), binding.logoImg);
                        }
                    }

                });
    }

    private void getUnreadNum() {
        if (loginBean == null) {
            return;
        }
        ServiceFactory.getService(IMainService.class)
                .getUnreadNum(loginBean.getToken(), loginBean.getClinicId())
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<Integer> responseData) {
                        if (responseData != null) {
                            binding.messageCountView.setBadgeCount(responseData.getData());
                        }
                    }

                });
    }



    private void setMenu() {
        List<MenuItemBean> menuList = DataCache.getMenuList();
        if (menuList == null || menuList.isEmpty()) {
            return;
        }
        binding.workspaceLayout.setVisibility(View.GONE);
        binding.executeLayout.setVisibility(View.GONE);
        binding.pharmacyLayout.setVisibility(View.GONE);
        for (int i = 0; i < menuList.size(); i++) {
            if (TextUtils.equals(menuList.get(i).getPerms(), AppConstant.MENU_DASHBOARD)) {
                binding.workspaceLayout.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals(menuList.get(i).getPerms(), AppConstant.MENU_EXECUTE)) {
                binding.executeLayout.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals(menuList.get(i).getPerms(), AppConstant.MENU_PHARMACY)) {
                binding.pharmacyLayout.setVisibility(View.VISIBLE);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateMessageCount(UpdateMessageCountEvent event) {
        getUnreadNum();
    }
}
